package threadcoreknowledge.stopthreads;

/**
 * 描述：     注意Thread.interrupted()方法的目标对象是“当前线程”，而不管本方法来自于哪个对象。
 * 代码出自Java并发编程之美1.7线程中断，感谢作者翟陆续
 *
 * Thread.interrupted() 静态方法,作用对象是"执行该方法所在的当前线程"
 *  1. 若调用该方法之前被interrupt过,则此方法返回true,并且清除掉当前线程的interrupt状态.当前线程的isInterrupted的判断也会变为false.
 *      后续继续调用Thread.interrupted() 方法,则会返回false.
 *  2. 若调用该方法之前没有被interrupt过,则此方法返回false.
 *
 */
public class RightWayInterrupted {

    public static void main(String[] args) throws InterruptedException {

        Thread threadOne = new Thread(new Runnable() {
            @Override
            public void run() {
                for (; ; ) {
                }
            }
        });

        // 启动线程
        threadOne.start();
        //设置中断标志
        threadOne.interrupt();
//        Thread.currentThread().interrupt();
        //获取中断标志
        System.out.println("1-isInterrupted: " + threadOne.isInterrupted()); // true
        //获取中断标志并重置
        System.out.println("2-interrupted: " + threadOne.interrupted()); // false
        System.out.println("3-interrupted: " + threadOne.interrupted()); // false
        System.out.println("3-interrupted: " + threadOne.interrupted()); // false
        System.out.println("333-interrupted: " + Thread.currentThread().isInterrupted()); // false
        Thread.currentThread().interrupt();
        System.out.println("333-interrupted: " + Thread.currentThread().isInterrupted()); // true
        System.out.println("4-interrupted: " + threadOne.interrupted());  // true
        System.out.println("333-interrupted: " + Thread.currentThread().isInterrupted()); // false
        //获取中断标志并重直
        System.out.println("5-interrupted: " + Thread.interrupted());  // false
        System.out.println("5-interrupted: " + Thread.interrupted());  // false
        //获取中断标志
        System.out.println("6-isInterrupted: " + threadOne.isInterrupted()); // true
        threadOne.join();
        System.out.println("Main thread is over.");
    }
}
